package top.yongyan0624.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.Alipay;
import top.yongyan0624.entity.Goods;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2021/9/11
 **/
@RestController
@RequestMapping("/order")
public class AlipayController extends BaseController {
    @PostMapping("/alipay")
    @Transactional
    public String alipay(@RequestBody Alipay alipay) throws AlipayApiException {
        //修改商品状态
        Map<Long, Integer> goodsMap = alipay.getGoodsMap();
        List<Goods> goodsList = goodsService.listByIds(goodsMap.keySet());
        goodsList.forEach(goods -> {
            if (goods.getAmount() <= 0) {
                throw new RuntimeException("商品:[" + goods.getTitle() + "]数量不足");
            }
            goods.setAmount(goods.getAmount() - goodsMap.get(goods.getId()));

        });
        goodsService.updateBatchById(goodsList);

        //设置订单号
        alipay.setOutTradeNo(UUID.randomUUID().toString());

        //设置订单名称
        String subject = StringUtils.join(
                goodsList
                        .stream()
                        .map(goods -> "[" + goods.getTitle() + "]*" + goodsMap.get(goods.getId()))
                        .collect(Collectors.toList()), ",");
        alipay.setSubject(subject);

        //设置付款金额
        double amount = goodsList
                .stream()
                .mapToDouble(value -> value.getPrice() * goodsMap.get(value.getId()))
                .sum();
        alipay.setTotalAmount(new DecimalFormat("#.00").format(amount));

        //设置商品描述
        alipay.setBody(subject + "已售出,总价：" + amount);

        //设置goodsIds
        String goodsIds = StrUtil.join(",", alipay.getGoodsMap().keySet());
        alipay.setGoodsIds(goodsIds);

        //订单持久化
        alipayService.save(alipay);

        return alipayService.aliPay(alipay);
    }

    @GetMapping("/listByUserId")
    public Result listByUserId(String subject, String userId) {
        Page<Alipay> pageData = alipayService.page(getPage(), new QueryWrapper<Alipay>()
                .eq("user_id", userId).like(StrUtil.isNotBlank(subject), "subject", subject));

        pageData.getRecords().forEach(a -> {
            List<String> goodsIdList = StrUtil.split(a.getGoodsIds(), ',', true, true);
            List<Goods> goodsList = goodsService.list(new QueryWrapper<Goods>()
                    .in("id", goodsIdList).orderByDesc("create_time"));
            goodsList.forEach(g -> {
                g.setUser(sysUserService.getById(g.getUserId()));
                g.setImgList(StrUtil.split(g.getImg(), ',', true, true));
            });

            a.setUser(sysUserService.getById(a.getUserId()));
            a.setGoodsList(goodsList);
        });

        return Result.success(pageData);
    }
}
